package com.mashibing.juc.c_007;

import java.util.concurrent.Semaphore;

/**
 * @ClassName T02_Semaphore
 * @Description 信号源 -------------限流
 * @Author xiongwei.wu
 * @Date 2021/7/12 16:41
 **/
public class T02_Semaphore {
    public static void main(String[] args) {
        //允许两个线程同事执行
//        Semaphore semaphore = new Semaphore(2);

        //使用公平锁，默认非公平
        Semaphore semaphore = new Semaphore(2, true);

        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("T1 running...");
                Thread.sleep(200);
                System.out.println("T1 running...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }).start();

        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("T2 running...");
                Thread.sleep(200);
                System.out.println("T2 running...");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
